package com.krtech.wecard.module.sys.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.krtech.wecard.framework.aop.Metrics;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.model.PageResponse;
import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.model.ResultTree;
import com.krtech.wecard.module.sys.entity.SysPower;
import com.krtech.wecard.module.sys.entity.SysRole;
import com.krtech.wecard.module.sys.entity.SysRolePower;
import com.krtech.wecard.module.sys.pojo.MenuVo;
import com.krtech.wecard.module.sys.pojo.MenuVoInfo;
import com.krtech.wecard.module.sys.service.ISysMenuService;
import com.krtech.wecard.module.sys.service.ISysRolePowerService;
import com.krtech.wecard.module.sys.service.ISysRoleService;
import com.krtech.wecard.utils.TreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色前端控制器
 * </p>
 *
 * @author laker
 * @since 2021-08-11
 */
@RestController
@RequestMapping("/sys/role")
@Api(tags = "角色管理")
public class SysRoleController {
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysMenuService sysMenuService;
    @Autowired
    ISysRolePowerService sysRolePowerService;

//    @GetMapping
//    @ApiOperation(value = "分页查询")
//    public PageResponse pageAll(@RequestParam(required = false, defaultValue = "1") long current,
//                                @RequestParam(required = false, defaultValue = "10") long size,
//                                Integer roleType) {
//        Page roadPage = new Page<>(current, size);
//        LambdaQueryWrapper<SysRole> queryWrapper = new QueryWrapper().lambda();
//        queryWrapper.eq(roleType != null, SysRole::getRoleType, roleType);
//        Page pageList = sysRoleService.page(roadPage, queryWrapper);
//        return PageResponse.ok(pageList.getRecords(), pageList.getTotal());
//    }
    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public Page<SysRole> page(Page<SysRole> page,Integer roleType,String keyword) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        if (roleType != null){
            queryWrapper.eq("role_type",roleType);
        }

        if (StrUtil.isNotEmpty(keyword)){
            queryWrapper.like("role_name",keyword);
        }

        Page<SysRole> rolePage = sysRoleService.page(page, queryWrapper);
        return rolePage;
    }


    @GetMapping("/list")
    @ApiOperation(value = "list")
    public List<SysRole> list(String keyword) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(keyword)){
            wrapper.like("role_name",keyword)
                    .or()
                    .like("role_code",keyword);
        }
        List<SysRole> list = sysRoleService.list(wrapper);
        return list;
    }

    @PostMapping
    @ApiOperation(value = "新增或者更新")
//    @SaCheckPermission("role.update")
    public CommRes saveOrUpdate(@RequestBody SysRole param) {
        return CommRes.ok(sysRoleService.saveOrUpdate(param));
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public CommRes get(@PathVariable Long id) {
        return CommRes.ok(sysRoleService.getById(id));
    }


    /**
     * 根据角色id查询角色权限
     * 如果角色是菜单角色 则剔除数据权限
     * 如果角色是数据权限 则剔除非数据权限
     *
     * @param roleId
     * @return
     */
    @GetMapping("/getRolePower")
    @ApiOperation(value = "根据角色id查询角色权限")
    public CommRes<MenuVoInfo> getRolePower(Long roleId) {
        SysRole role = sysRoleService.getById(roleId);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
//        List<SysPower> allPower = null;
//        // 菜单角色
//        if (role.getRoleType().equals(SysRole.ROLE_TYPE_MENU)) {
//            allPower = sysMenuService.list(Wrappers.<SysPower>lambdaQuery().ne(SysPower::getType, 3));
//        } else {
//            allPower = sysMenuService.list(Wrappers.<SysPower>lambdaQuery().ne(SysPower::getType, 2));
//        }
//
//        List<SysRolePower> myPower = sysRolePowerService.list(Wrappers.<SysRolePower>lambdaQuery().eq(SysRolePower::getRoleId, roleId));
//        allPower.forEach(sysPower -> {

//            myPower.forEach(sysRolePower -> {
//                if (sysRolePower.getPowerId().equals(sysPower.getMenuId())) {
//                    sysPower.setCheckArr("1");
//                }
//            });
//        });

        List<SysRolePower> myPower = sysRolePowerService.list(new QueryWrapper<SysRolePower>()
                .eq("role_id",roleId));


        List<Long> collect = myPower.stream().map(SysRolePower::getPowerId).collect(Collectors.toList());
        List<SysPower> menuList = null;

        if (collect.size() > 0){
            menuList = sysMenuService.list(new QueryWrapper<SysPower>().in("menu_id", collect));
        }else {
            menuList = new ArrayList<>();
        }

        List<MenuVo> menuInfo = menuList.stream().map(one -> {
            MenuVo menuVO = new MenuVo();
            BeanUtil.copyProperties(one, menuVO);
            menuVO.setId(one.getMenuId());
            return menuVO;
        }).collect(Collectors.toList());

        MenuVoInfo menuVoInfo = new MenuVoInfo();

        List<MenuVo> menuVos = TreeUtil.toTree(menuInfo, 0L);
        menuVoInfo.setTree(menuVos);

        List<Long> menuIdList = menuList.stream().map(SysPower::getMenuId).collect(Collectors.toList());
        menuVoInfo.setList(menuIdList);

        return CommRes.ok(menuVoInfo);
    }

    @PutMapping("/saveRolePower")
    @ApiOperation(value = "保存角色权限数据")
//    @SaCheckPermission("role.update.power")
    @Transactional(rollbackFor = Exception.class)
    public CommRes saveRolePower(Long roleId, String powerIds) {
        List<String> stringList = Arrays.asList(powerIds.split(","));
        sysRolePowerService.remove(Wrappers.<SysRolePower>lambdaQuery().eq(SysRolePower::getRoleId, roleId));
        List<SysRolePower> rolePowers = new ArrayList<>();
        stringList.forEach(powerId -> {
            SysRolePower sysRolePower = new SysRolePower();
            sysRolePower.setRoleId(roleId);
            sysRolePower.setPowerId(Long.valueOf(powerId));
            rolePowers.add(sysRolePower);
        });
        boolean saveBatch = sysRolePowerService.saveBatch(rolePowers);
        return CommRes.ok(saveBatch);
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除")
//    @SaCheckPermission("role.delete")
    public CommRes delete(@PathVariable Long id) {
        return CommRes.ok(sysRoleService.removeById(id));
    }
}